#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstdlib>
#include "Common.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

namespace SocketModule
{
    using namespace LogModule;
    const static int gbacklog = 16;
    // 模版方法实现
    class Socket
    {
    public:
        virtual ~Socket() {}
        virtual void SocketOrDie() = 0;
        virtual void BindOrDie(uint16_t port) = 0;
        virtual void ListenOrDie(int backlog) = 0;
        virtual std::shared_ptr<Socket> Accept(InetAddr *client) = 0;
        virtual void Close() = 0;
        virtual int Recv(std::string *out) = 0;
        virtual int Send(const std::string &in) = 0;
        virtual int Connect(const std::string &server_ip, uint16_t server_port) = 0;
    public:
        void BuidTcpSocketMethod(uint16_t port, int backlog = gbacklog)
        {
            SocketOrDie();
            BindOrDie(port);
            ListenOrDie(backlog);
        }
        void BuidTcpClientSocketMethod()
        {
            SocketOrDie();
        }
        // void BuidUdpSocketMethod()
        // {
        //     SocketOrDie();
        //     BindOrDie();
        // }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int sockfd) : _sockfd(sockfd) {}
        TcpSocket() : _sockfd(-1) {}
        ~TcpSocket() {}
        void SocketOrDie() override
        {
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if(_sockfd < 0)
            {
                LOG(LogLevel::ERROR) << "create socket error";
                exit(SOCKET_ERR);
            }
            LOG(LogLevel::INFO) << "create socket success";
        }
        void BindOrDie(uint16_t port) override
        {
            InetAddr localaddr(port);
            int n = bind(_sockfd, localaddr.NetAddrPtr(), localaddr.NetAddrLen());
            if(n < 0)
            {
                LOG(LogLevel::ERROR) << "bind socket error";
                exit(BIND_ERR);
            }
            LOG(LogLevel::INFO) << "bind socket success";
        }
        void ListenOrDie(int backlog) override
        {
            int n = listen(_sockfd, backlog);
            if(n < 0)
            {
                LOG(LogLevel::ERROR) << "listen socket error";
                exit(LISTEN_ERR);
            }
            LOG(LogLevel::INFO) << "listen socket success";
        }

        int Recv(std::string *out) override
        {
            char buffer[4096];
            int n = ::recv(_sockfd, buffer, sizeof(buffer) - 1, 0);
            if(n > 0)
            {
                buffer[n] = 0;
                *out += buffer;
            }

            return n;
        }

        int Send(const std::string &in) override
        {
            return ::send(_sockfd, in.c_str(), in.size(), 0);
        }

        std::shared_ptr<Socket> Accept(InetAddr *client) override
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int fd = accept(_sockfd, CONV(peer), &len);
            if(fd < 0)
            {
                LOG(LogLevel::WARNING) << "accept socket warning...";
                return nullptr;
            }
            client->SetAddr(peer);

            return std::make_shared<TcpSocket>(fd);
        }
        int Connect(const std::string &server_ip, uint16_t server_port) override
        {
            InetAddr server(server_ip, server_port);
            int n = ::connect(_sockfd, server.NetAddrPtr(), server.NetAddrLen());
            if(n < 0)
            {
                LOG(LogLevel::ERROR) << "connect socket error";
                exit(CONNECT_ERR);
            }
            return n;
        }

        void Close()
        {
            if(_sockfd >= 0)
                ::close(_sockfd);
        }
    private:
        int _sockfd;
    };
}